package com.cy.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cy.entity.JsonResult;
import com.cy.entity.Meetingroom;
import com.cy.entity.Order_list;
import com.cy.service.ManagerService;
import com.cy.service.MeetingroomService;
import com.cy.service.Order_listService;
import com.cy.service.TypeService;
import com.qiniu.util.Json;

@RestController
public class Order_listController {

	@Autowired
	private Order_listService order_listService;
	@Autowired
	private MeetingroomService meetingroomService;
	@Autowired
	private TypeService typeService;
	@Autowired
	private ManagerService managerService;
	
	//查询该会议室相关预约信息
	@RequestMapping("roomOrderInfo")
	public JsonResult roomOrderInfo(Integer mid) {
		//获取当前会议室的所有预约
		System.out.println(mid);
		List<Order_list> list = order_listService.findOrderByState(0);
		List<Order_list> list1 = order_listService.findOrderByState(1);
		List<Order_list> list2 = order_listService.findOrderByState(2);
		list.addAll(list1);
		list.addAll(list2);
		//获取会议室信息
		Meetingroom meetingroom = meetingroomService.findMeetingroomById(mid);
		
		
		//获取会议室开放时间小时-结束时间小时
		int startHour = meetingroom.getOpendate().getHours();
		int endHour = meetingroom.getClosedate().getHours();
		System.out.println(startHour+" "+endHour);
		
		//二维数组的行数
		int hang = endHour - startHour;
		
		
        Calendar instanceStart = Calendar.getInstance();
        instanceStart.setTime(new Date());
        instanceStart.add(Calendar.DATE,+1);
        instanceStart.set(Calendar.HOUR_OF_DAY,startHour);
        instanceStart.set(Calendar.MINUTE,00);
        instanceStart.set(Calendar.SECOND,00);
        instanceStart.set(Calendar.MILLISECOND,000);
        
        Calendar instanceEnd = Calendar.getInstance();
        instanceEnd.setTime(new Date());
        instanceEnd.add(Calendar.DATE,+6);
        instanceEnd.set(Calendar.HOUR_OF_DAY,endHour);
        instanceEnd.set(Calendar.MINUTE,00);
        instanceEnd.set(Calendar.SECOND,00);
        instanceEnd.set(Calendar.MILLISECOND,000);
        
        
        System.out.println("as"+instanceStart.get(Calendar.HOUR_OF_DAY));
        
        String[][] orderInfo = new String[hang][6];
        System.out.println(orderInfo.length+" "+orderInfo[0].length+" "+list.size());
        
        //获取第一个时间段
//        int sdatetime = instanceStart.get(Calendar.DATE);
//        System.out.println(sdatetime);
        
        for(int i=0; i<orderInfo.length ;i++) {
        	
        	Date d1 = instanceStart.getTime();
        	instanceStart.set(Calendar.HOUR_OF_DAY,instanceStart.get(Calendar.HOUR_OF_DAY)+1);
        	Date d2 = instanceStart.getTime();
        	if(instanceStart.get(Calendar.HOUR_OF_DAY) > instanceEnd.get(Calendar.HOUR_OF_DAY)) {
        		break;
        	}
        	
        	//判断当前时间段是否有预约       	       	
        	for(int j=0; j<orderInfo[i].length; j++) {
        		if(j==0) {
        			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        	        String d1s = sdf.format(d1);
        	        String d2s = sdf.format(d2);
        			orderInfo[i][j] = d1s+"-"+d2s;
        		}
        		else {
        		System.out.println("date"+instanceStart.get(Calendar.DATE)+ "time"+instanceStart.get(Calendar.HOUR_OF_DAY)+"\n");
        		
        		
        		
        		int isok = order_listService.judgeTime(list, d1.getTime(), d2.getTime());
        		instanceStart.set(Calendar.DATE,instanceStart.get(Calendar.DATE)+1);
        		instanceStart.set(Calendar.HOUR_OF_DAY,instanceStart.get(Calendar.HOUR_OF_DAY)-1);
        		d1 = instanceStart.getTime();
        		instanceStart.set(Calendar.HOUR_OF_DAY,instanceStart.get(Calendar.HOUR_OF_DAY)+1);
        		d2 = instanceStart.getTime();
        		orderInfo[i][j] = ""+isok;
        		}
        	}
        	instanceStart.set(Calendar.DATE,instanceStart.get(Calendar.DATE)-5);
        	System.out.println("\n");
        }
        
        Date time = instanceStart.getTime();
        System.out.println(time);
        String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(time);
        System.out.println(formatDate);
        
		return new JsonResult(orderInfo);
	}
	
	//下单预约
	@RequestMapping("addOrder")
	public JsonResult addOrder(Integer mid, Integer userId, String subject, String name, String tel, double Allprice, String remarks,
			int status, String startTime, String endTime) {
		
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date date2 = null;
		Date date1 = null;
		try {
			date1 = ft.parse(startTime);
			date2 = ft.parse(endTime);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		Order_list ol = new Order_list(0, userId, mid, subject, name, tel, remarks, Allprice, status, new Date(), date1, date2);
		
		System.out.println(ol);
		
		if (order_listService.judgeTime(order_listService.findOrder_listByMid(mid) , 
				ol.getStarttime().getTime(), ol.getEndtime().getTime())==1) {
			return new JsonResult<>(1,"该时间段以及被让他人预约！请参照预约信息表重新预约");
		}
		order_listService.addOrder(ol);
		return new JsonResult<>(0,"预约成功");
	}
	
	//更新预约单状态（半小时未受理预约将自动受理）
//	@RequestMapping("orderReFresh")
//	public JsonResult orderReFresh() {
//		order_listService.orderReFresh();
//		try {
//			Thread.sleep(1000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		System.out.println("ReFresh order!");
//		orderReFresh();
//		return new JsonResult<>(0,"OK");
//	}
	
	//获取指定用户的所有订单信息
	@RequestMapping("findOrderInfoByUserId")
	public JsonResult findOrderInfoByUserId(Integer userId) {
		List<Order_list> list = order_listService.findUserOrder(userId);
		if(list.size()==0) {
			return new JsonResult(1,"无任何相关预约");
		}
		
		List<Map<String, Object>> returnList = new ArrayList<Map<String,Object>>();
		for (Order_list order_list : list) {
			Map<String, Object> map= new HashMap<String, Object>();
			map.put("room", meetingroomService.findMeetingroomById(order_list.getMid()));
			map.put("type", typeService.findTypeById(meetingroomService.findMeetingroomById(order_list.getMid()).getTypeid()));
			map.put("manager", managerService.findManagerById(meetingroomService.findMeetingroomById(order_list.getMid()).getManagerid()));
			map.put("orderInfo", order_list);
			returnList.add(map);
		}
		return new JsonResult(returnList);
	}
	
	//根据订单状态获取用户的订单信息
	@RequestMapping("findOrderInfoByUserIdAndStatus")
	public JsonResult findOrderInfoByUserIdAndStatus(Integer userId, int status) {
			List<Order_list> list = order_listService.findUserOrderByStatus(userId, status);
			
			List<Map<String, Object>> returnList = new ArrayList<Map<String,Object>>();
			for (Order_list order_list : list) {
				Map<String, Object> map= new HashMap<String, Object>();
				map.put("room", meetingroomService.findMeetingroomById(order_list.getMid()));
				map.put("type", typeService.findTypeById(meetingroomService.findMeetingroomById(order_list.getMid()).getTypeid()));
				map.put("manager", managerService.findManagerById(meetingroomService.findMeetingroomById(order_list.getMid()).getManagerid()));
				map.put("orderInfo", order_list);
				returnList.add(map);
			}
		return new JsonResult(returnList);
	}
	
	//获取全部订单信息
	@RequestMapping("findAllOrderInfo")
	public JsonResult findAllOrderInfo() {
		List<Order_list> list = order_listService.findAllOrder_list();
		List<Map<String, Object>> returnList = new ArrayList<Map<String,Object>>();
		for (Order_list order_list : list) {
			Map<String, Object> map= new HashMap<String, Object>();
			map.put("room", meetingroomService.findMeetingroomById(order_list.getMid()));
			map.put("type", typeService.findTypeById(meetingroomService.findMeetingroomById(order_list.getMid()).getTypeid()));
			map.put("manager", managerService.findManagerById(meetingroomService.findMeetingroomById(order_list.getMid()).getManagerid()));
			map.put("orderInfo", order_list);
			returnList.add(map);
		}
		return new JsonResult(returnList);
	}
	
	
	//支付预约
	@RequestMapping("makeOrder")
	public JsonResult makeOrder(@RequestBody Map<String, Object> map) {
//		map.get("orderId");
		Order_list order_list = order_listService.findOrder_listById(Integer.parseInt((String)map.get("orderId")));
		order_list.setStatus(1);
		System.out.println(order_list);
		order_listService.updateOrder(order_list);
		return new JsonResult(0,"ok");
	}
	
	//取消订单
	@RequestMapping("cancelOrder")
	public JsonResult cancelOrder(@RequestBody Map<String, Object> map) {
		Order_list order_list = order_listService.findOrder_listById(Integer.parseInt((String)map.get("orderId")));
		order_list.setStatus(-1);
		System.out.println(order_list);
		order_listService.updateOrder(order_list);
		return new JsonResult(0,"ok");
	}
	//同意预约请求
	@RequestMapping("orderConfirm")
	public JsonResult orderConfirm(@RequestBody Map<String, Object> map) {
		Order_list order_list = order_listService.findOrder_listById(Integer.parseInt((String)map.get("orderId")));
		order_list.setStatus(2);
		System.out.println(order_list);
		order_listService.updateOrder(order_list);
		return new JsonResult(0,"ok");
	}
	
	//通过订单状态获取所有订单
	@RequestMapping("showOrderByState")
	public JsonResult showOrderByState() {
		List<Map<String, List<Order_list>>> list = new ArrayList<>();
		
		Map<String, List<Order_list>> state1 = new HashMap<>();
		List<Order_list> list1 = order_listService.findOrderByState(0);
		state1.put("state0", list1);
		list.add(state1);
		
		Map<String, List<Order_list>> state2 = new HashMap<>();
		List<Order_list> list2 = order_listService.findOrderByState(1);
		state2.put("state1", list2);
		list.add(state2);
		
		Map<String, List<Order_list>> state3 = new HashMap<>();
		List<Order_list> list3 = order_listService.findOrderByState(2);
		state3.put("state2", list3);
		list.add(state3);
		
		Map<String, List<Order_list>> state4 = new HashMap<>();
		List<Order_list> list4 = order_listService.findOrderByState(3);
		state4.put("state3", list4);
		list.add(state4);
		
		Map<String, List<Order_list>> state5 = new HashMap<>();
		List<Order_list> list5 = order_listService.findOrderByState(-1);
		state5.put("state_1", list5);
		list.add(state5);
		
		return new JsonResult<>(list);
	}
	
	@RequestMapping("findOrder_listById")
	public JsonResult findOrder_listById(Integer id) {
		if (id==null) {
			List<Order_list> list = order_listService.findAllOrder_list();
			return new JsonResult<>(list);
		}
		Order_list ol = order_listService.findOrder_listById(id);
		return new JsonResult<>(ol);
	}
	
	@RequestMapping("findOrderByStatus/{status}")
	public JsonResult findOrderByStatus(@PathVariable("status") Integer status) {
		List<Order_list> list = order_listService.findOrderByState(status);
		return new JsonResult<>(list);
	}
}
